package com.example.tools;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2018/12/12
 * @Description: 排序工具類
 **/
public class SortListTools {

    public static final String DESC = "desc";
    public static final String ASC = "asc";

    /**
     * 对list中的元素进行排序.
     *
     * @param list  排序集合
     * @param field 排序字段
     * @param sort  排序方式: SortList.DESC(降序) SortList.ASC(升序).
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<?> sort(List<?> list, final String field, final String sort) {
        Collections.sort(list, (a, b) -> {
            int ret = 0;
            try {
                Field f = a.getClass().getDeclaredField(field);
                f.setAccessible(true);
                Class<?> type = f.getType();
                if (type == int.class) {
                    ret = ((Integer) f.getInt(a)).compareTo(f.getInt(b));
                } else if (type == double.class) {
                    ret = ((Double) f.getDouble(a)).compareTo(f.getDouble(b));
                } else if (type == long.class) {
                    ret = ((Long) f.getLong(a)).compareTo(f.getLong(b));
                } else if (type == float.class) {
                    ret = ((Float) f.getFloat(a)).compareTo(f.getFloat(b));
                } else if (type == Date.class) {
                    ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
                } else {
                    ret = Integer.valueOf(String.valueOf(f.get(a))).compareTo(Integer.valueOf((String.valueOf(f.get(b)))));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (sort != null && sort.toLowerCase().equals(DESC)) {
                return -ret;
            } else {
                return ret;
            }
        });
        return list;
    }
}
